import {
	config
} from "@/utils/config.js"
import 
	store
 from "@/store/index.js"
//获取当前年月日
function getCurrentDate() {
	const currentDate = new Date();
	const year = currentDate.getFullYear();
	let month = currentDate.getMonth() + 1;
	month = month < 10 ? '0' + month : month;
	let day = currentDate.getDate();
	day = day < 10 ? '0' + day : day;
	const date = `${year}-${month}-${day}`;
	return date;
}

function uuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}
/**上传图片
* @param {Object} url 上传地址
* @param {Object} folder 上传文件夹
* @param {Object} isWatermark 是否给上传图片加水印 默认为true
*/
export function ossUpload(url, folder,isWatermark=true) {
	const ossConfig = config.ossConfig;
	const lastSlashIndex = url.lastIndexOf("."); // 获取最后一个 "/" 的索引位置
	const imageName = url.substr(lastSlashIndex, url.length - 1);
	const pathName = `${folder}/${getCurrentDate()}/${uuid()}${imageName}`;
	const dir = `${ossConfig.dir}${pathName}`;
	let params = {
		dir: dir,
		env: ossConfig.env,
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: ossConfig.host,
			data: params,
			method: 'GET',
			header: {
				"content-type": "application/json"
			},
			success: (res) => {
				if (res.statusCode == 200) {
					let ossInfo = res.data;
					console.log(ossInfo, 'ossInfo')
					uni.uploadFile({
						url: ossInfo.host,
						filePath: url,
						name: 'file',
						formData: {
							key: ossInfo.dir,
							policy: ossInfo.policy,
							OSSAccessKeyId: ossInfo.accessid,
							signature: ossInfo.signature,
							success_action_status: 200
						},
						success: (result) => {
							if (result && result.statusCode == 200) {
								let fileUrl =isWatermark?`${ossInfo.host}/${ossInfo.dir}?x-oss-process=style/${store.state.company.watermark}`: `${ossInfo.host}/${ossInfo.dir}`;
								resolve(fileUrl)
							} else {
								reject(url)
							}
						},
						fail: (err) => {
							reject(url)
						}
					});
				} else {
					reject(url)
				}
			},
			fail: (err) => {
				reject(err);
			},
		});
	});

}